<template>
  <div class="visitor-alreadyVisited">
    <div class="search-group">
      <div class="input-wrap">
        <div class="label">姓名:</div>
        <div class="input-item">
          <a-input allowClear :maxLength="30" clearable v-model="queryParam.name" placeholder="请填写" />
        </div>
      </div>
      <div class="input-wrap">
        <div class="label">身份证号:</div>
        <div class="input-item">
          <a-input allowClear :maxLength="30" clearable v-model="queryParam.idCard" placeholder="请填写" />
        </div>
      </div>
      <!-- <div class="input-wrap">
        <div class="label">责任医疗机构:</div>
        <div class="input-item">
          <a-input allowClear :maxLength="30" clearable v-model="queryParam.departmentName" placeholder="请填写" />
        </div>
      </div> -->
      <!-- <div class="input-wrap">
        <div class="label">责任民警:</div>
        <div class="input-item">
          <a-input allowClear :maxLength="30" clearable v-model="queryParam.helpName" placeholder="请填写" />
        </div>
      </div> -->
      <div class="input-wrap">
        <div class="label">风险等级:</div>
        <div class="input-item">
          <a-select allowClear v-model="queryParam.levelType" placeholder="请选择">
            <a-select-option v-for="(item, index) in riskList" :key="index" :value="item.levelType">
              {{ item.levelName }}
            </a-select-option>
          </a-select>
        </div>
      </div>
      <div class="input-wrap">
        <div class="label">人员标签:</div>
        <div class="input-item">
          <el-cascader
            style="width: 300px"
            clearable
            class="my-cascader"
            ref="cascader"
            placeholder="请选择"
            v-model="cascader_value"
            :options="cascader_options"
            @change="cascader_change"
            :props="{ multiple: true, expandTrigger: 'hover' }"
          ></el-cascader>
        </div>
      </div>

      <div class="input-wrap">
        <div class="label">添加时间:</div>
        <div class="time-item">
          <start-end-time
            :times="times"
            :showTime="{ format: 'HH:mm:ss' }"
            format="YYYY-MM-DD HH:mm:ss"
            @timeChange="timeChange"
            :resetTime="resetTime"
          ></start-end-time>
        </div>
      </div>
      <div class="btn-wrap">
        <a-button class="searchBtn" @click="searchQuery()" type="primary"> 搜索 </a-button>
        <a-button class="resetBtn" @click="searchReset()" type="primary"> 重置 </a-button>
      </div>
    </div>
    <div>
      <a-table
        ref="table"
        rowKey="id"
        class="tableList"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
        :scroll="{ x: 1000 }"
      >
        <template slot="action" slot-scope="records">
          <span class="operation deatil-color" @click="handleDetail(records)">全息档案</span>
          <span class="operation deatil-color" @click="handleEdit(records)">编辑</span>
          <!--  <span class="operation deatil-color" v-if="records.isBingding == '1'" @click="handleRemoveDevice(records)"
            >解绑设备</span
          > -->
          <span class="operation deatil-color" @click="handleDelete(records)">删除</span>
        </template>
      </a-table>
    </div>
    <!-- <Detail type="repair" ref="rentDetailRef" /> -->
    <BindingPersonnel ref="bindingPersonnelRef" />
    <allMessage
      ref="allMessage"
      :title="confirmTitle"
      :content="confirmContent"
      :publicVisible="publicVisible"
      @cancel="publicVisible = false"
      @tipMessage="tipMessage"
    ></allMessage>
    <Add ref="addRef" @refresh="loadData" />
  </div>
</template>

<script>
import startEndTime from '@/components/startEndTime'
import { JeecgListMixinNew } from '@/mixins/JeecgListMixinNew'
import { getCommunityList, getDictItemsFromCache, getSubordinateList, getRiskLevels } from '@/api/api'
// import Detail from './detail.vue'
import { handleSelectChange } from '../../../../utils/util'
import moment from 'moment'
import BindingPersonnel from './bindingPersonnel'
import allMessage from '@/components/allMessage'
import { postAction, getAction } from '@/api/manage'
import Add from './add.vue'
import { Cascader, Select, Option } from 'element-ui'
export default {
  name: 'room',
  components: {
    startEndTime,
    BindingPersonnel,
    allMessage,
    Add,
    'el-cascader': Cascader,
    'el-select': Select,
    'el-option': Option,
  },
  mixins: [JeecgListMixinNew],

  props: {
    idCode: {
      type: String,
      default: '',
    },
    villageList: {
      type: Array,
      default: () => [],
    },
    activeIndex: {
      type: Number,
      default: 0,
    },
    youthIds: {
      type: Array,
      default: () => [],
    },
    caseSelectValue: {
      type: Array,
      default: () => [],
    },
  },

  watch: {
    idCode(newVal) {
      console.log(newVal, 'idCode')
      this.extendParams.policeAgencyId = newVal
      this.loadData()
    },
    institution: {
      type: Object,
      default: () => ({}),
    },
    youthIds(newVal) {
      console.log('监听youthids', newVal)
      this.queryParam.youthType = newVal

      //this.loadData()
    },
    // caseSelectValue(newVal) {
    //   //el-cascader 不回显，99% 是因为“选项还没来，值就先来了”。
    //   console.log('监听caseSelectValue', newVal)
    //   if (this.cascader_options.length > 0) {
    //     this.cascader_value = newVal
    //   } else {
    //     this._pendingCaseSelectValue = newVal //先缓存
    //   }
    //   //this.cascader_value = newVal
    // },
  },
  data() {
    return {
      url: {
        list: '/qnMinor/selectListMinorpage',
      },
      cascader_value: [],
      cascader_options: [],
      _pendingCaseSelectValue: null,
      apiPaths: {
        0: '/qnMinor/selectListMinorpage', // 青少年接口
        1: '/web/qnAdult/selectListAdultpage', //青壮年接口
      },
      cuscader_value: [],
      disableMixinCreated: true,
      columns: [
        {
          title: '序号',
          align: 'center',
          width: 80,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
          fixed: 'left',
        },
        {
          title: '姓名',
          dataIndex: 'name',
          ellipsis: true,
          align: 'center',
          width: 100,
          customRender: (t) => {
            return (
              <a-tooltip placement="top">
                <template slot="title">
                  <span>{t}</span>
                </template>
                <div class="ant-table-row-cell-ellipsis">{t}</div>
              </a-tooltip>
            )
          },
        },
        {
          title: '年龄',
          dataIndex: 'age',
          ellipsis: true,
          align: 'center',
          width: 100,
          customRender: (t) => {
            return (
              <a-tooltip placement="top">
                <template v-slot:title>
                  <span>{t}</span>
                </template>
                <div class="ant-table-row-cell-ellipsis">{t}</div>
              </a-tooltip>
            )
          },
        },
        {
          title: '性别 ',
          dataIndex: 'sex',
          ellipsis: true,
          align: 'center',
          width: 100,
          customRender: function (t, r, index) {
            return t == 1 ? '男' : '女'
          },
          /*  customRender: (t) => {
            return (
              <a-tooltip placement="top">
                <template slot="title">
                  <span>{t}</span>
                </template>
                <div class="ant-table-row-cell-ellipsis">{t}</div>
              </a-tooltip>
            )
          }, */
        },
        {
          title: '身份证号',
          dataIndex: 'idCard',
          ellipsis: true,
          align: 'center',
          customRender: (t) => {
            return (
              <a-tooltip placement="top">
                <template slot="title">
                  <span>{t}</span>
                </template>
                <div class="ant-table-row-cell-ellipsis">{t}</div>
              </a-tooltip>
            )
          },
          width: 180,
        },
        {
          title: '人员标签',
          dataIndex: 'youthTypeName',
          ellipsis: true,
          align: 'center',
          /*  customRender: (t) => {
            const tags = t.split(',')
            console.log(tags, 'tags')

            return (
              <div style="display: flex; flex-wrap: wrap; gap: 4px;">
                {tags.map((tag) => (
                  <a-tag color="#108ee9">{tag}</a-tag>
                ))}
              </div>
            )
          }, */
          customRender: (t) => {
            const tags = t ? t.split(',') : []
            return (
              <div style="display: flex; flex-wrap: wrap; gap: 4px;">
                {tags.map((tag) => {
                  const showText = tag.length > 8 ? `${tag.slice(0, 8)}...` : tag
                  return (
                    <a-tooltip title={tag} placement="top" color="transparent">
                      <a-tag color="#108ee9">{showText}</a-tag>
                    </a-tooltip>
                  )
                })}
              </div>
            )
          },
          width: 120,
        },

        {
          title: '风险等级',
          dataIndex: 'levelNname',
          ellipsis: true,
          align: 'center',
          customRender: (t, r) => {
            return <a-tag color={r.levelColor}>{r.levelNname}</a-tag>
          },
          width: 160,
        },
        /* {
          title: '责任民警',
          dataIndex: 'responsiblePolice',
          ellipsis: true,
          align: 'center',
          customRender: (t, r) => {},
          width: 160,
        }, */

        {
          title: '创建时间',
          dataIndex: 'createTime',
          ellipsis: true,
          align: 'center',
          customRender: (t) => {
            return (
              <a-tooltip placement="top">
                <template slot="title">
                  <span>{t}</span>
                </template>
                <div class="ant-table-row-cell-ellipsis">{t}</div>
              </a-tooltip>
            )
          },
          width: 190,
        },
        /* {
          title: '关怀记录',
          dataIndex: 'helpCount',
          ellipsis: true,
          align: 'center',
          customRender: (t) => {
            return (
              <a-tooltip placement="top">
                <template slot="title">
                  <span>{t}</span>
                </template>
                <div class="ant-table-row-cell-ellipsis">{t}</div>
              </a-tooltip>
            )
          },
          width: 160,
        }, */
        /* {
          title: '创建时间',
          dataIndex: 'createTime',
          ellipsis: true,
          align: 'center',
          width: 180,
          customRender: (t) => {
            return (
              <a-tooltip placement="top">
                <template slot="title">
                  <span>{t}</span>
                </template>
                <div class="ant-table-row-cell-ellipsis">{t}</div>
              </a-tooltip>
            )
          },
        }, */
        /* {
          title: '更新时间',
          dataIndex: 'updateTime',
          ellipsis: true,
          align: 'center',
          width: 180,
        }, */
        {
          title: '操作',
          scopedSlots: { customRender: 'action' },
          ellipsis: true,
          align: 'center',
          width: 220,
          fixed: 'right',
        },
      ],
      project_company_type: [],
      times: {},
      buildingList: [],
      unitList: [],
      floorList: [],
      roomList: [],
      isPost: true,
      //isPost:false,
      queryParam: {
        name: '',
        sex: '',
        idCard: '',
        //  mobile: undefined,
        levelType: '',
        // youthType: [],
      },
      flagTypeList: [],
      extendParams: {},
      reasonForReporting: [],
      bindingPersonnelRef: null,
      publicVisible: false,
      confirmTitle: '',
      confirmContent: '',
      addRef: null,
      riskList: [],
      //beforeFetch: true,
      lastNode: [],
      deepNodes: [],
    }
  },
  mounted() {
    // this.getFiveList()
    // this.getRisks()
    Promise.all([this.getFiveList(), this.getRisks()])
  },
  inject: ['provideData'],
  computed: {
    filteredColumns() {
      return this.columns.filter((column) => {
        // 如果是姓名列，根据 showNameColumn 决定是否显示
        if (column.dataIndex === 'phone') {
          return !this.activeIndex //0显示
        }
        // 其他列默认显示
        return true
      })
    },
  },
  methods: {
    // * 处理行业树 将children:[] 项过滤
    process_cascader_data(data) {
      if (!data || !Array.isArray(data)) {
        return null
      }
      return data.map((item) => {
        const processedItem = {
          parentId: item.t.parentId,
          label: item.t.dictName,
          value: item.t.dictCode,
          children: item.children.length > 0 ? item.children : null, // 将 children 设置为 null
        }

        if (item.children && item.children.length > 0) {
          processedItem.children = this.process_cascader_data(item.children) // 递归处理子节点
        }

        return processedItem
      })
    },
    /*  async getFiveList() {
      let { result } = await ajaxGetDictItems({ code: 'five_green_types' })
      this.fiveList = result
    }, */
    async getFiveList() {
      let { result } = await getAction('/sysMultiLevelDict/selectSysMultiLevelDictList', { dictCode: 'PREVENT_CRIME' })
      console.log(result, 'result')
      let final_result = this.process_cascader_data(result[0].children)
      console.log(final_result, 'final_result')

      this.cascader_options = final_result
      console.log(this.caseSelectValue, 'kkkkkkkk')
      if (this.caseSelectValue) {
        this.cascader_value = this.caseSelectValue
      }
      // if (this._pendingCaseSelectValue) {
      //   this.cascader_value = this._pendingCaseSelectValue
      //   this._pendingCaseSelectValue = null // 用完清空
      // } else if (this.caseSelectValue?.length) {
      //   this.cascader_value = this.caseSelectValue
      // }
    },
    // * 级联选择框变化时触发
    cascader_change(e) {
      console.log('级联选择框变化了', e, this.cascader_value)

      /*   console.log(e[0], this.queryParam.youthType, '选中节点')
      if (!e[0]) {
        this.lastNode = []
        this.queryParam.youthType = ''
      } else {
        console.log(this.$refs.cascader.getCheckedNodes(true), '方法名') //只选最深的节点
        const lastNode = this.$refs.cascader.getCheckedNodes(true)
        this.lastNode = lastNode.map((item) => {
          return { label: item.label, value: item.value }
        })
        this.form.youthType = this.lastNode[0].value
        this.queryParam.youthType = this.lastNode[0].value
      } */
      this.deepNodes = e.map((item) => item[item.length - 1])
      console.log(this.deepNodes, 'shen')

      this.queryParam.youthType = this.deepNodes

      console.log(this.queryParam, 'queryParam')

      this.queryParam.policeAgencyId = this.idCode

      this.loadData()
    },
    async getRisks() {
      try {
        const { result } = await getRiskLevels({ levelCode: 'minor_risk' })
        this.riskList = result
      } catch (error) {}
    },
    handleDetail(records) {
      console.log(records, 'records')

      const flag = records.youthType.includes('PJD')

      //  const flag = ['PJD'].includes(records.youthType)

      this.$router.push({
        path: flag ? '/careFamily/teenagerProfile/detail' : '/careFamily/youngAdultsProfile/detail',
        query: {
          id: records.id,
        },
      })
    },
    searchReset() {
      if (!this.idCode) {
        this.$message.error('请选择机关信息!')
        return
      }
      if (this.resetTime !== undefined) {
        this.resetTime = true
      }
      this.queryParam = {}
      this.loadData(1)
    },
    handleSelectChange,
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    /*  searchQuery() {
      console.log('搜索',this.queryParam)
      if (!this.idCode) {
        this.$message.error('请选择机关信息!')
        return
      }
    //  this.queryParam.youthType = this.lastNode[0]?.value
     // this.queryParam.policeAgencyId = this.idCode
      this.loadData(1)
    }, */
    timeChange(v, index) {
      if (index == 1) {
        this.queryParam.startTime = this.$moment(v).valueOf()
      } else {
        this.queryParam.endTime = this.$moment(v).valueOf()
      }
      if (v == null) {
        this.queryParam.startTime = null
        this.queryParam.endTime = null
      }
    },
    async initPage() {
      try {
        console.log(res)
      } catch (error) {
      } finally {
      }
    },
    handleBindPatient(records) {
      this.$refs.bindingPersonnelRef.show(records)
    },
    handleDelete(records) {
      this.publicVisible = true
      this.confirmTitle = '删除'
      this.confirmContent = '请确认是否删除？'
      this.$refs.allMessage.show(records)
    },
    async tipMessage(records) {
      let res
      if (this.confirmTitle == '删除') {
        res = await getAction('/qnMinor/deletMinor', { id: records.id })
      } else if (this.confirmTitle == '解绑设备') {
        res = await postAction('/wb/device/bingding', {
          deviceId: records.deviceId,
          mentalPatientPersonId: records.id,
          type: 2,
        })
      }
      this.$message.success(res.message)
      this.publicVisible = false
      this.searchQuery()
    },
    handleRemoveDevice(records) {
      this.publicVisible = true
      this.confirmTitle = '解绑设备'
      this.confirmContent = '请确认是否解绑设备？'
      this.$refs.allMessage.show(records)
    },
    handleEdit(records) {
      this.$refs.addRef.show(records, 'edit')
    },
  },
}
</script>
<style lang="less" scoped>
.visitor-alreadyVisited {
  position: relative;
  .my-cascader {
    /deep/ .el-cascader__tags {
      max-height: 60px !important;
      overflow-y: auto;
    }
  }
}
</style>
